﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace UDPClient
{
    internal class Program
    {
        static void Main(string[] args)
        {
            byte[] data = new byte[1024];
            string strInput, strData;
            // 定义一个源IP地址
            // Parse:IP地址字符串转换为IPAdress实例
            IPEndPoint ClientIP = new IPEndPoint(IPAddress.Parse("127.0.0.1"),9050);
            // 定义一个基于UDP协议的Socket
            Socket ClientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
            string strWelcome = "Hello are you Here?";
            data = Encoding.ASCII.GetBytes(strWelcome);
            // 向服务器发送指定字节的数据
            ClientSocket.SendTo(data,data.Length, SocketFlags.None,ClientIP);
            IPEndPoint IPSender = new IPEndPoint(IPAddress.Any,0);
            EndPoint IPRemote = (EndPoint)IPSender;
            data = new byte[1024];
            int nRevByte = ClientSocket.ReceiveFrom(data,ref IPRemote);
            Console.WriteLine("Receive Data From Server:{0}", IPRemote.ToString());
            Console.WriteLine(Encoding.ASCII.GetString(data,0, nRevByte));
            while (true)
            {
                // 从标准输入流中读取下一行字符
                strInput = Console.ReadLine();
                if(strInput=="exit")
                    break;
                // 将从控制台中获取的数据发送到服务器端,并且接收服务器端发回的数据
                ClientSocket.SendTo(Encoding.ASCII.GetBytes(strInput), IPRemote);
                data = new byte[1024];
                nRevByte= ClientSocket.ReceiveFrom(data, ref IPRemote);
                strData= Encoding.ASCII.GetString(data,0, nRevByte);
                Console.WriteLine(strData);
            }
            Console.WriteLine("StopClient");
            ClientSocket.Close();
        }
    }
}
